// pages/my/buy-list/buy-list.js
const app = getApp();
Page({
  data: {
    monthlyRecords: [],
    screenHeight: app.globalData.safearea.height
  },
  onLoad () {
    // 页面加载时的初始化操作
    wx.showLoading();
    this.loadData();
  },
  loadData() {
    const that = this;
    app.request('/api/user/order', {}).then(res => {
      let data = [];
      let format_data_arr = [];
      let monthlyRecords = {}; // 最终数据形态
      for (let i = 0;i < res.data.data.length;i++) {
        let item = res.data.data[i];
        if (item.paytime) {
          let objectDate = new Date(item.paytime);
          item.format_date = objectDate.getFullYear() + '年' + (objectDate.getMonth()+1) + '月';
          data.push(item);
          let fres = format_data_arr.filter((itemFormat) => {
            return itemFormat.month === item.format_date;
          });
          if (fres.length === 0) {
            format_data_arr.push({
              month: item.format_date,
              expanded: true,
              records: []
            });
          }
        }
      }
      for (let i = 0;i < data.length;i++) {
        let item = data[i];
        if (!(item.format_date in monthlyRecords)) {
          monthlyRecords[item.format_date] = [item]
        } else {
          monthlyRecords[item.format_date].push(item);
        }
      }
      for (const item in monthlyRecords) {
        for (let i = 0;i < format_data_arr.length;i++) {
          if (item === format_data_arr[i].month) {
            format_data_arr[i].records = monthlyRecords[item];
            break;
          }
        }
      }
      that.setData({
        monthlyRecords: format_data_arr
      });
      console.log('orderList', format_data_arr);
      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
      console.error(err);
    });
  },
  toggleMonth: function (e) {
    const month = e.currentTarget.dataset.month;
    const monthlyRecords = this.data.monthlyRecords.map(item => {
      if (item.month === month) {
        item.expanded = !item.expanded;
      }
      return item;
    });
    this.setData({
      monthlyRecords
    });
  },
  // 更多功能函数可以在这里添加
})